package 网络编程项目.login.utiles;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class ClientToSendFile {

  public static String sendFile(String path) {
    String image = "";
    try {
      SocketChannel socketChannel = SocketChannel.open();
      socketChannel.socket().connect(new InetSocketAddress("127.0.0.1", 8888));
      File file = new File(path);
      FileChannel fileChannel = new FileInputStream(file).getChannel();
      ByteBuffer buffer = ByteBuffer.allocate(100);
      socketChannel.read(buffer);
      buffer.flip();
      image = (new String(buffer.array(), 0, buffer.limit(), Charset.forName("utf-8")));
      buffer.clear();
      int num = 0;
      while ((num = fileChannel.read(buffer)) > 0) {
        buffer.flip();
        socketChannel.write(buffer);
        buffer.clear();
      }
      if (num == -1) {
        fileChannel.close();
        socketChannel.shutdownOutput();
      }
      socketChannel.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return image;
  }
}

